package com.jingdianjichi.subject.util;

import com.jingdianjichi.subject.service.EmployeeDomainService;
import lombok.SneakyThrows;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.client.Request;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.CreateIndexResponse;
import org.elasticsearch.client.indices.GetIndexRequest;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

import static com.jingdianjichi.subject.config.HotelConstants.MAPPING_TEMPLATE;
@Component
public class RestIndexClientUtil {
    @Resource
    private RestHighLevelClient restHighLevelClient;





    /**
     * 初始化索引库
     */
    @SneakyThrows
    public CreateIndexResponse createIndex(String indexName) {
        if (indexName == null && indexName.trim().length() == 0) {
            throw new IllegalArgumentException("indexName不能为空");
        }
        CreateIndexRequest source = new CreateIndexRequest(indexName).source(MAPPING_TEMPLATE, XContentType.JSON);
        CreateIndexResponse createIndexResponse = restHighLevelClient.indices().create(source, RequestOptions.DEFAULT);
        boolean success = createIndexResponse.isAcknowledged();
        if (success) {
            System.out.println("索引库创建成功");
        } else {
            System.out.println("索引库创建失败");
        }
        return createIndexResponse;
    }
    /**
     * 删除索引库
     */
    @SneakyThrows
    public void deleteIndex(String indexName) {
        //获取索引库
        GetIndexRequest getIndexRequest = new GetIndexRequest(indexName);
        boolean exists = restHighLevelClient.indices().exists(getIndexRequest, RequestOptions.DEFAULT);
        if (!exists) {
            throw new IllegalArgumentException("索引库不存在");
        }
        DeleteIndexRequest deleteIndexRequest = new DeleteIndexRequest(indexName);
        restHighLevelClient.indices().delete(deleteIndexRequest, RequestOptions.DEFAULT);
        System.out.println("索引库删除成功");

    }





}
